import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:family_app/src/features/finance/models/transaction_model.dart';
import 'package:family_app/src/features/finance/models/monthly_bill_model.dart';
import 'package:family_app/src/features/finance/models/yearly_stats_model.dart';
import 'package:family_app/src/features/finance/models/bill_detail_model.dart';
import 'package:family_app/src/features/finance/models/account_model.dart';
import 'package:family_app/src/features/finance/models/budget_model.dart';
import 'package:family_app/src/features/finance/services/finance_service.dart';

/// 当前选择的月份提供者
final selectedMonthProvider = StateProvider<DateTime>((ref) => DateTime.now());

/// 交易记录列表提供者
final transactionsProvider =
    FutureProvider.autoDispose<List<TransactionModel>>((ref) async {
  final financeService = ref.watch(financeServiceProvider);
  final selectedMonth = ref.watch(selectedMonthProvider);
  return financeService.getTransactionsByMonth(
    selectedMonth.year,
    selectedMonth.month,
  );
});

/// 指定日期范围的交易记录列表提供者
final monthTransactionsProvider = FutureProvider.autoDispose.family<List<TransactionModel>, (DateTime, DateTime)>(
  (ref, dateRange) async {
    final financeService = ref.watch(financeServiceProvider);
    final (startDate, endDate) = dateRange;
    return financeService.getTransactionsByDateRange(startDate, endDate);
  },
);

/// 指定日期范围和分类的交易记录列表提供者
final categoryTransactionsProvider = FutureProvider.autoDispose.family<List<TransactionModel>, ((DateTime, DateTime), String)>(
  (ref, params) async {
    final financeService = ref.watch(financeServiceProvider);
    final ((startDate, endDate), category) = params;
    final transactions = await financeService.getTransactionsByDateRange(startDate, endDate);
    return transactions.where((tx) => tx.category == category).toList();
  },
);

/// 所有分类列表提供者
final allCategoriesProvider = FutureProvider.autoDispose<List<String>>((ref) async {
  final financeService = ref.watch(financeServiceProvider);
  return financeService.getAllCategories();
});

/// 月度收入提供者
final monthlyIncomeProvider = FutureProvider.autoDispose<int>((ref) async {
  final financeService = ref.watch(financeServiceProvider);
  final selectedMonth = ref.watch(selectedMonthProvider);
  final startDate = DateTime(selectedMonth.year, selectedMonth.month, 1);
  final endDate = DateTime(selectedMonth.year, selectedMonth.month + 1, 0);
  return financeService.getTotalIncome(startDate: startDate, endDate: endDate);
});

/// 指定日期范围的收入提供者
final monthIncomeProvider = FutureProvider.autoDispose.family<int, (DateTime, DateTime)>(
  (ref, dateRange) async {
    final financeService = ref.watch(financeServiceProvider);
    final (startDate, endDate) = dateRange;
    return financeService.getTotalIncome(startDate: startDate, endDate: endDate);
  },
);

/// 月度支出提供者
final monthlyExpenseProvider = FutureProvider.autoDispose<int>((ref) async {
  final financeService = ref.watch(financeServiceProvider);
  final selectedMonth = ref.watch(selectedMonthProvider);
  final startDate = DateTime(selectedMonth.year, selectedMonth.month, 1);
  final endDate = DateTime(selectedMonth.year, selectedMonth.month + 1, 0);
  return financeService.getTotalExpense(startDate: startDate, endDate: endDate);
});

/// 指定日期范围的支出提供者
final monthExpenseProvider = FutureProvider.autoDispose.family<int, (DateTime, DateTime)>(
  (ref, dateRange) async {
    final financeService = ref.watch(financeServiceProvider);
    final (startDate, endDate) = dateRange;
    return financeService.getTotalExpense(startDate: startDate, endDate: endDate);
  },
);

/// 月度余额提供者
final monthlyBalanceProvider = FutureProvider.autoDispose<int>((ref) async {
  final financeService = ref.watch(financeServiceProvider);
  final selectedMonth = ref.watch(selectedMonthProvider);
  final startDate = DateTime(selectedMonth.year, selectedMonth.month, 1);
  final endDate = DateTime(selectedMonth.year, selectedMonth.month + 1, 0);
  return financeService.getBalance(startDate: startDate, endDate: endDate);
});

/// 指定日期范围的余额提供者
final monthBalanceProvider = FutureProvider.autoDispose.family<int, (DateTime, DateTime)>(
  (ref, dateRange) async {
    final financeService = ref.watch(financeServiceProvider);
    final (startDate, endDate) = dateRange;
    return financeService.getBalance(startDate: startDate, endDate: endDate);
  },
);

/// 年度收入提供者
final yearIncomeProvider = FutureProvider.autoDispose.family<int, (DateTime, DateTime)>(
  (ref, dateRange) async {
    final financeService = ref.watch(financeServiceProvider);
    final (startDate, endDate) = dateRange;
    return financeService.getTotalIncome(startDate: startDate, endDate: endDate);
  },
);

/// 年度支出提供者
final yearExpenseProvider = FutureProvider.autoDispose.family<int, (DateTime, DateTime)>(
  (ref, dateRange) async {
    final financeService = ref.watch(financeServiceProvider);
    final (startDate, endDate) = dateRange;
    return financeService.getTotalExpense(startDate: startDate, endDate: endDate);
  },
);

/// 支出分类统计提供者
final expenseCategoryStatsProvider =
    FutureProvider.autoDispose<Map<String, int>>((ref) async {
  final financeService = ref.watch(financeServiceProvider);
  final selectedMonth = ref.watch(selectedMonthProvider);
  final startDate = DateTime(selectedMonth.year, selectedMonth.month, 1);
  final endDate = DateTime(selectedMonth.year, selectedMonth.month + 1, 0);
  return financeService.getCategoryStats(
    type: TransactionType.expense,
    startDate: startDate,
    endDate: endDate,
  );
});

/// 收入分类统计提供者
final incomeCategoryStatsProvider =
    FutureProvider.autoDispose<Map<String, int>>((ref) async {
  final financeService = ref.watch(financeServiceProvider);
  final selectedMonth = ref.watch(selectedMonthProvider);
  final startDate = DateTime(selectedMonth.year, selectedMonth.month, 1);
  final endDate = DateTime(selectedMonth.year, selectedMonth.month + 1, 0);
  return financeService.getCategoryStats(
    type: TransactionType.income,
    startDate: startDate,
    endDate: endDate,
  );
});

/// 交易操作状态提供者
final transactionOperationProvider = StateNotifierProvider<
    TransactionOperationNotifier, TransactionOperationState>((ref) {
  final financeService = ref.watch(financeServiceProvider);
  return TransactionOperationNotifier(financeService, ref);
});

/// 交易操作状态管理器
class TransactionOperationNotifier
    extends StateNotifier<TransactionOperationState> {
  final FinanceService _financeService;
  final Ref _ref;

  TransactionOperationNotifier(this._financeService, this._ref)
      : super(const TransactionOperationState.initial());

  /// 添加交易记录
  Future<TransactionModel?> addTransaction({
    required int amount,
    required TransactionType type,
    required String category,
    String? description,
    DateTime? transactionDate,
  }) async {
    state = const TransactionOperationState.loading();
    try {
      final transaction = await _financeService.addTransaction(
        amount: amount,
        type: type,
        category: category,
        description: description,
        transactionDate: transactionDate,
      );

      if (transaction != null) {
        state = const TransactionOperationState.success('交易记录添加成功');
        _refreshProviders();
        return transaction;
      } else {
        state = const TransactionOperationState.error('交易记录添加失败');
        return null;
      }
    } catch (e) {
      state = TransactionOperationState.error('交易记录添加失败: ${e.toString()}');
      return null;
    }
  }

  /// 更新交易记录
  Future<TransactionModel?> updateTransaction({
    required String id,
    int? amount,
    TransactionType? type,
    String? category,
    String? description,
    DateTime? transactionDate,
  }) async {
    state = const TransactionOperationState.loading();
    try {
      final transaction = await _financeService.updateTransaction(
        id: id,
        amount: amount,
        type: type,
        category: category,
        description: description,
        transactionDate: transactionDate,
      );

      if (transaction != null) {
        state = const TransactionOperationState.success('交易记录更新成功');
        _refreshProviders();
        return transaction;
      } else {
        state = const TransactionOperationState.error('交易记录更新失败');
        return null;
      }
    } catch (e) {
      state = TransactionOperationState.error('交易记录更新失败: ${e.toString()}');
      return null;
    }
  }

  /// 删除交易记录
  Future<bool> deleteTransaction(String id) async {
    state = const TransactionOperationState.loading();
    try {
      final success = await _financeService.deleteTransaction(id);

      if (success) {
        state = const TransactionOperationState.success('交易记录删除成功');
        _refreshProviders();
        return true;
      } else {
        state = const TransactionOperationState.error('交易记录删除失败');
        return false;
      }
    } catch (e) {
      state = TransactionOperationState.error('交易记录删除失败: ${e.toString()}');
      return false;
    }
  }

  /// 刷新提供者
  void _refreshProviders() {
    _ref.invalidate(transactionsProvider);
    _ref.invalidate(monthTransactionsProvider);
    _ref.invalidate(monthlyIncomeProvider);
    _ref.invalidate(monthIncomeProvider);
    _ref.invalidate(monthlyExpenseProvider);
    _ref.invalidate(monthExpenseProvider);
    _ref.invalidate(monthlyBalanceProvider);
    _ref.invalidate(monthBalanceProvider);
    _ref.invalidate(expenseCategoryStatsProvider);
    _ref.invalidate(incomeCategoryStatsProvider);
    _ref.invalidate(allCategoriesProvider);
    _ref.invalidate(yearlyBillListProvider);
  }

  /// 标记消息已显示
  void markMessageShown() {
    state = state.copyWithMessageShown();
  }
}

/// 年度账单列表提供者
final yearlyBillListProvider = FutureProvider.autoDispose.family<List<MonthlyBillModel>, (int, int)>(
  (ref, params) async {
    final financeService = ref.watch(financeServiceProvider);
    final (year, userId) = params;
    return financeService.getMonthlyBillList(year: year, userId: userId);
  },
);

/// 年度统计数据提供者
final yearlyStatsProvider = FutureProvider.autoDispose.family<YearlyStatsModel?, (int, int)>(
  (ref, params) async {
    final financeService = ref.watch(financeServiceProvider);
    final (year, userId) = params;
    return financeService.getYearlyStats(year: year, userId: userId);
  },
);

/// 详细账单列表提供者
final billDetailListProvider = FutureProvider.autoDispose.family<BillDetailData?, (int, int, int, String)>(
  (ref, params) async {
    final financeService = ref.watch(financeServiceProvider);
    final (userId, type, secondClassifyId, date) = params;
    return financeService.getBillDetailList(
      userId: userId,
      type: type,
      secondClassifyId: secondClassifyId,
      date: date,
    );
  },
);

/// 交易操作状态
class TransactionOperationState {
  final bool isLoading;
  final bool isSuccess;
  final String? message;
  final String? error;
  final bool isMessageShown;

  const TransactionOperationState({
    required this.isLoading,
    required this.isSuccess,
    this.message,
    this.error,
    this.isMessageShown = false,
  });

  /// 初始状态
  const TransactionOperationState.initial()
      : isLoading = false,
        isSuccess = false,
        message = null,
        error = null,
        isMessageShown = false;

  /// 加载中状态
  const TransactionOperationState.loading()
      : isLoading = true,
        isSuccess = false,
        message = null,
        error = null,
        isMessageShown = false;

  /// 成功状态
  const TransactionOperationState.success(String this.message)
      : isLoading = false,
        isSuccess = true,
        error = null,
        isMessageShown = false;

  /// 错误状态
  const TransactionOperationState.error(String this.error)
      : isLoading = false,
        isSuccess = false,
        message = null,
        isMessageShown = false;

  /// 标记消息已显示
  TransactionOperationState copyWithMessageShown() {
    return TransactionOperationState(
      isLoading: isLoading,
      isSuccess: isSuccess,
      message: message,
      error: error,
      isMessageShown: true,
    );
  }
}

// ==================== 新增 Provider (账户、预算管理) ====================

/// 账户列表提供者
/// 用于管理用户的所有账户（现金、银行卡、支付宝等）
final accountsProvider = StateNotifierProvider<
    AccountNotifier,
    List<AccountModel>
>((ref) => AccountNotifier());

/// 账户状态管理器
class AccountNotifier extends StateNotifier<List<AccountModel>> {
  AccountNotifier() : super([]);

  /// 添加账户
  void addAccount(AccountModel account) {
    state = [...state, account];
  }

  /// 删除账户
  void deleteAccount(String id) {
    state = state.where((a) => a.id != id).toList();
  }

  /// 更新账户
  void updateAccount(AccountModel account) {
    state = [
      for (final a in state)
        if (a.id == account.id) account else a,
    ];
  }

  /// 获取总资产
  double getTotalBalance() {
    return state.fold(0, (sum, account) => sum + account.balance);
  }
}

/// 预算列表提供者
/// 用于管理用户的各个分类预算
final budgetsProvider = StateNotifierProvider<
    BudgetNotifier,
    List<BudgetModel>
>((ref) => BudgetNotifier());

/// 预算状态管理器
class BudgetNotifier extends StateNotifier<List<BudgetModel>> {
  BudgetNotifier() : super([]);

  /// 添加预算
  void addBudget(BudgetModel budget) {
    state = [...state, budget];
  }

  /// 更新预算
  void updateBudget(BudgetModel budget) {
    state = [
      for (final b in state)
        if (b.id == budget.id) budget else b,
    ];
  }

  /// 删除预算
  void deleteBudget(String id) {
    state = state.where((b) => b.id != id).toList();
  }

  /// 获取指定月份的预算
  List<BudgetModel> getBudgetsByMonth(int year, int month) {
    return state.where((b) => b.year == year && b.month == month).toList();
  }
}

/// 总资产提供者
/// 计算所有账户的总余额
final totalAssetsProvider = Provider<double>((ref) {
  final accounts = ref.watch(accountsProvider);
  return accounts.fold(0, (sum, account) => sum + account.balance);
});

/// 月度预算统计提供者
/// 计算指定月份的预算统计信息
final monthlyBudgetStatsProvider = Provider.family<
    Map<String, dynamic>,
    (int, int)
>((ref, params) {
  final (year, month) = params;
  final budgets = ref.watch(budgetsProvider);
  final monthBudgets = budgets.where((b) => b.year == year && b.month == month).toList();

  final totalBudget = monthBudgets.fold(0.0, (sum, b) => sum + b.budgetAmount);
  final totalSpent = monthBudgets.fold(0.0, (sum, b) => sum + b.spentAmount);
  final overBudgetCount = monthBudgets.where((b) => b.isOverBudget).length;

  return {
    'totalBudget': totalBudget,
    'totalSpent': totalSpent,
    'remaining': totalBudget - totalSpent,
    'percentage': totalBudget > 0 ? (totalSpent / totalBudget * 100).clamp(0, 100) : 0,
    'overBudgetCount': overBudgetCount,
  };
});
